from flask import Blueprint, render_template, jsonify, request
from app.models import Auth
from app.forms import AddMenuForm
from flask_login import login_required

auth_controller = Blueprint("menu", __name__)

@auth_controller.route("/index")
@login_required
def index():
    return render_template("menu/index.html")

@auth_controller.route('/lst')
@login_required
def lst():
    data = Auth.auth_tree()
    return jsonify({"code": 0, "msg": "获取成功", "data": data})

@auth_controller.route("/add", methods=["GET", "POST"])
@login_required
def add():
    id = request.args.get('id', 0, type=int)
    form = AddMenuForm()
    if request.method == "POST":
        if form.validate_on_submit():
            parent_id = request.form.get('parent_id')
            name = form.name.data
            url = request.form.get('url')
            status = request.form.get('status')
            sort = request.form.get('sort')
            is_menu = request.form.get('is_menu')

            auth = Auth(parent_id=parent_id, name = name, url = url, status = status, sort = sort, is_menu = is_menu)
            Auth.add_menu(auth)
            return jsonify({"code": 1, "msg": "添加成功"})
        else:
            return jsonify({"code": 0, "msg": "添加失败 - " + str(form.errors)})
    
    menu = Auth.auth_tree2()
    parent = None
    if id > 0:
        parent = Auth.get_auth_by_id(id)
    return render_template("menu/add.html", form = form, menu = menu, parent = parent)

@auth_controller.route("/edit", methods=["GET", "POST"])
@login_required
def edit():
    form = AddMenuForm()
    id = request.args.get('id', 0, type=int)
    auth = Auth.get_auth_by_id(id)
    if request.method == "POST":
        if form.validate_on_submit():
            parent_id = request.form.get('parent_id')
            name = form.name.data
            url = request.form.get('url')
            status = request.form.get('status')
            sort = request.form.get('sort')
            is_menu = request.form.get('is_menu')

            auth.parent_id = parent_id
            auth.name = name
            auth.url = url
            auth.status = status
            auth.sort = sort
            auth.is_menu = is_menu
            Auth.update_auth()
            return jsonify({"code": 1, "msg": "修改成功"})
        else:
            return jsonify({"code": 0, "msg": "修改失败 - " + str(form.errors)})

    menu = Auth.auth_tree2()
    return render_template("menu/edit.html", form = form, menu = menu, auth_data = auth)

@auth_controller.route("/delete_op", methods=["POST"])
@login_required
def delete_op():
    id = request.form.get("id", 0, type=str).split(",")
    result = Auth.delete_auth_by_id(id)
    if result == -1:
        return jsonify({"code": 0, "msg": "有子级菜单，不能删除"})
    return jsonify({"code": 1, "msg": "删除成功"})